import React, { useState, useEffect } from 'react';
import axios from 'axios';
import pinyin from 'pinyin';

import Dhat from './Dhat';
import './Contacts.css';

interface UserData {
  username: string;
  image: string;
  isLoggedIn: boolean;
}

interface User {
  _id: string;
  username: string;
  image: string;
}

interface ContactsProps {
  currentUser: UserData;
}

const Contacts: React.FC<ContactsProps> = ({ currentUser }) => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [searchTerm, setSearchTerm] = useState('');

  // 获取用户列表（除了自己）
  useEffect(() => {
    const fetchUsers = async () => {
      try {
        setLoading(true);
        const response = await axios.get(
          `http://localhost:3001/ysx/users?currentUser=${currentUser?.username || ''}`
        );
        if (response.data.code === 200) {
          // 过滤掉当前用户
          const filteredUsers = response.data.data.filter(
            (user: User) => user.username !== (currentUser?.username || '')
          );
          setUsers(filteredUsers);
        } else {
          setError(response.data.msg);
        }
      } catch (error) {
        console.error('获取用户列表失败:', error);
        setError('获取用户列表失败');
      } finally {
        setLoading(false);
      }
    };

    if (currentUser?.username) {
      fetchUsers();
    } else {
      setLoading(false);
      setError('用户信息无效');
    }
  }, [currentUser?.username]);

  // 处理用户点击
  const handleUserClick = (user: User) => {
    console.warn('选择联系人:', user.username);
    setSelectedUser(user);
  };

  // 返回通讯录列表
  const handleBack = () => {
    setSelectedUser(null);
  };

  // 过滤用户列表（支持搜索）
  const filteredUsers = users.filter(user =>
    user.username.toLowerCase().includes(searchTerm.toLowerCase())
  );

  // 获取中文名字的拼音首字母
  const getPinyinFirstLetter = (chineseName: string): string => {
    const firstChar = chineseName.charAt(0);

    // 如果是英文字母，直接返回大写
    if (/[a-zA-Z]/.test(firstChar)) {
      return firstChar.toUpperCase();
    }

    // 如果是中文字符，使用pinyin库转换
    if (/[\u4e00-\u9fa5]/.test(firstChar)) {
      try {
        const pinyinResult = pinyin(firstChar, {
          style: pinyin.STYLE_FIRST_LETTER, // 只取首字母
          heteronym: false, // 不显示多音字
        });

        if (pinyinResult && pinyinResult[0] && pinyinResult[0][0]) {
          const firstLetter = pinyinResult[0][0].toUpperCase();
          console.warn(
            `中文名字 "${chineseName}" 的第一个字 "${firstChar}" 转换为拼音首字母: "${firstLetter}"`
          );
          return firstLetter;
        }
      } catch (error) {
        console.error('拼音转换失败:', error);
      }
    }

    // 其他字符返回#
    console.warn(
      `特殊字符名字 "${chineseName}" 的第一个字符 "${firstChar}" 转换为: "#"`
    );
    return '#';
  };

  // 按用户名首字母分组
  const groupUsersByFirstLetter = () => {
    const grouped: { [key: string]: User[] } = {};

    filteredUsers.forEach(user => {
      const firstLetter = getPinyinFirstLetter(user.username);
      if (!grouped[firstLetter]) {
        grouped[firstLetter] = [];
      }
      grouped[firstLetter].push(user);
    });

    // 按字母顺序排序，特殊字符放在最后
    const sortedKeys = Object.keys(grouped).sort((a, b) => {
      if (a === '#') return 1;
      if (b === '#') return -1;
      return a.localeCompare(b);
    });

    return sortedKeys.reduce(
      (result, key) => {
        result[key] = grouped[key];
        return result;
      },
      {} as { [key: string]: User[] }
    );
  };

  // 如果选择了用户，显示聊天页面
  if (selectedUser) {
    return (
      <Dhat
        currentUser={currentUser}
        selectedUser={selectedUser}
        onBack={handleBack}
      />
    );
  }

  // 防护性检查 - 在渲染逻辑中
  if (!currentUser || !currentUser.username) {
    return (
      <div className="contacts-container">
        <div className="contacts-header">
          <h1 className="header-title">通讯录</h1>
        </div>
        <div className="error">
          <div>❌ 用户信息无效，请重新登录</div>
          <button
            onClick={() => (window.location.href = '/login')}
            className="retry-btn"
          >
            返回登录
          </button>
        </div>
      </div>
    );
  }

  const groupedUsers = groupUsersByFirstLetter();

  return (
    <div className="contacts-container">
      {/* 头部 */}
      <div className="contacts-header">
        <h1 className="header-title">通讯录功能</h1>
      </div>

      {/* 搜索框 */}
      <div className="search-container">
        <input
          type="text"
          placeholder="搜索联系人..."
          value={searchTerm}
          onChange={e => setSearchTerm(e.target.value)}
          className="search-input"
        />
      </div>

      {/* 联系人列表 */}
      <div className="contacts-list">
        {loading ? (
          <div className="loading">
            <div>🔄 加载中...</div>
          </div>
        ) : error ? (
          <div className="error">
            <div>❌ {error}</div>
            <button
              onClick={() => window.location.reload()}
              className="retry-btn"
            >
              重试
            </button>
          </div>
        ) : filteredUsers.length === 0 ? (
          <div className="no-contacts">
            <div>📭 {searchTerm ? '没有找到匹配的联系人' : '暂无联系人'}</div>
          </div>
        ) : (
          Object.entries(groupedUsers).map(([letter, userGroup]) => (
            <div key={letter} className="letter-group">
              <div className="letter-header">{letter}</div>
              {userGroup.map(user => (
                <div
                  key={user._id}
                  className="contact-item"
                  onClick={() => handleUserClick(user)}
                >
                  <div className="contact-avatar">
                    <img
                      src={user.image}
                      alt={user.username}
                      className="contact-avatar-img"
                    />
                  </div>
                  <div className="contact-info">
                    <div className="contact-name">{user.username}</div>
                  </div>
                </div>
              ))}
            </div>
          ))
        )}
      </div>
    </div>
  );
};

export default Contacts;
